package main

import (
	"context"
	wapi "dfs/server/master/api/worker"
	"dfs/server/worker/api"
	"dfs/server/worker/config"
	"dfs/server/worker/core"
	"dfs/server/worker/service"
	"fmt"
	"net"
	"time"

	"google.golang.org/grpc"
)

func heartbeat(gap int, stop <-chan struct{}) {
	conn, err := grpc.Dial(fmt.Sprintf("%s:%d", config.MasterIP, config.MasterPort), grpc.WithInsecure())
	if err != nil {
		fmt.Printf("无法连接Master节点@%s:%d\n", config.MasterIP, config.MasterPort)
	}
	defer conn.Close()
	client := wapi.NewWorkerServiceClient(conn)
	for {
		select {
		case <-stop:
			fmt.Println("停止发送心跳")
			return
		default:
			client.HeartBeat(context.Background(), &wapi.HeartBeatReq{
				Id:  fmt.Sprintf("%s:%d", config.IP, config.Port),
				Cap: int32(core.GetCap()),
			})
			time.Sleep(time.Duration(gap) * time.Second)
		}
	}
}

func main() {
	// stop signal
	stop := make(chan struct{})
	defer func(stop chan struct{}) {
		recover()
		close(stop)
	}(stop)

	// init worker
	core.Init()

	// heartbeat
	go heartbeat(3, stop)

	// start RPC-Server
	conn, err := net.Listen("tcp", fmt.Sprintf(":%d", config.Port))
	if err != nil {
		fmt.Println("监听端口失败")
		return
	}
	server := grpc.NewServer()
	api.RegisterClientServiceServer(server, &service.ClientService{})
	server.Serve(conn)
}
